// src/utils/exportExcel.js
import * as XLSX from 'xlsx';

export const useExportToExcel = (headers, data, fileName = 'exported-file') => {
  // 创建工作簿
  const workbook = XLSX.utils.book_new();

  // 创建工作表
  const worksheet = {};

  // 添加表头
  const headerRow = {};
  headers.forEach((header, index) => {
    headerRow[header.dataIndex] = header.title;
  });
  headers.forEach((header, colIndex) => {
    const cellAddress = XLSX.utils.encode_cell({ c: colIndex, r: 0 });
    worksheet[cellAddress] = { t: 's', v: header.title };
  });

  // 将数据添加到工作表的后续行
  data.forEach((row, rowIndex) => {
    Object.keys(headerRow).forEach((key, colIndex) => {
      worksheet[XLSX.utils.encode_cell({ c: colIndex, r: rowIndex + 1 })] = { t: 's', v: row[key] };
    });
    
  });
  // 设置工作表的范围
  worksheet['!ref'] = XLSX.utils.encode_range({
    s: { r: 0, c: 0 },
    e: { r: data.length, c: headers.length - 1 }
  });

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  // 导出 Excel 文件
  XLSX.writeFile(workbook, `${fileName}.xlsx`);
};